package com.wl156.activities.publish;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.wl156.BaseActivity;
import com.wl156.MyApp;
import com.wl156.lite.R;
import com.wl156.model.Certificate;
import com.wl156.model.User;
import com.wl156.model.WebServiceClient;
import com.wl156.widget.ProviceSelector;

public class NewGoodInfo extends BaseActivity implements OnClickListener {

	protected static final String TAG = NewGoodInfo.class.getSimpleName();

	private ProviceSelector mFromProviceSelector;
	private ProviceSelector mToProviceSelector;
	private EditText mName;
	private EditText mWeight;
	private EditText mLength;

	private EditText mNote;
	private Spinner mNeedCarModel;
	private EditText mNeddCarCount;
	// private EditText mFreightUnit;
	private Spinner mFreightUnitSpinner;
	RelativeLayout mFutureLayout;
	TextView mDateShow;

	private TextView mContact;
	private TextView mPhone;

	WebServiceClient mWebServiceClient;
	Certificate mCertificate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Window win = getWindow();
		// win.requestFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.act_new_good_info);
		// win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
		// R.drawable.ic_launcher);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		Button confirm = (Button) findViewById(R.id.confirm);
		confirm.setOnClickListener(this);

		mFromProviceSelector = (ProviceSelector) findViewById(R.id.provice_selector);
		mFromProviceSelector.setTitle("起点: ");
		mFromProviceSelector.setProviceRequried(true);
		mFromProviceSelector.setCityRequried(true);
		mToProviceSelector = (ProviceSelector) findViewById(R.id.to_provice_selector);
		mToProviceSelector.setTitle("终点: ");
		mToProviceSelector.setProviceRequried(true);
		mToProviceSelector.setCityRequried(true);

		mName = (EditText) findViewById(R.id.name);
		mWeight = (EditText) findViewById(R.id.weight);
		mLength = (EditText) findViewById(R.id.length);
		mNote = (EditText) findViewById(R.id.remark);
		mNeedCarModel = (Spinner) findViewById(R.id.need_car_model);
		mNeddCarCount = (EditText) findViewById(R.id.need_car_count);
		// mFreightUnit = (EditText) findViewById(R.id.freightUnit);
		mFreightUnitSpinner = (Spinner) findViewById(R.id.freightUnitSpinner);

		mContact = (TextView) findViewById(R.id.contact);
		mPhone = (TextView) findViewById(R.id.phone);

		mFutureLayout = (RelativeLayout) findViewById(R.id.future_layout);
		mDateShow = (TextView) findViewById(R.id.date_show);
		CheckBox futureCheck = (CheckBox) findViewById(R.id.check_future_info);
		futureCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				mFutureLayout.setVisibility(isChecked ? View.VISIBLE
						: View.GONE);
			}
		});
		Button selectDate = (Button) findViewById(R.id.select_date);
		selectDate.setOnClickListener(this);

		User user = ((MyApp) getApplication()).getCurrentUser();
		mContact.setText(user.name);
		mPhone.setText(user.phone);
		new GetNewGoodInfo().execute();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			final String startLocationLv1 = mFromProviceSelector.getProvice();
			final String startLocationLv2 = mFromProviceSelector.getCity();
			final String startLocationLv3 = mFromProviceSelector.getRegion();
			final String endLocationLv1 = mToProviceSelector.getProvice();
			final String endLocationLv2 = mToProviceSelector.getCity();
			final String endLocationLv3 = mToProviceSelector.getRegion();
			final String setOffDate = mDateShow.getText().toString();
			final String freightName = mName.getText().toString();
			final String freightTonnage = mWeight.getText().toString();
			final String freightTruckLengthRequired = mLength.getText()
					.toString();
			final String contactName = mContact.getText().toString();
			final String contactPhone = mPhone.getText().toString();
			final String attention = mNote.getText().toString();
			String tmp = "";
			if (mNeedCarModel.getSelectedItem() != null) {
				tmp = mNeedCarModel.getSelectedItem().toString();
			}
			final String freightTruckTypeRequired = tmp;
			final String freightTruckAmountRequired = mNeddCarCount.getText()
					.toString();
			// final String freightUnit = mFreightUnit.getText().toString();
			// if (!TextUtils.isEmpty(freightUnit)
			// && !(freightUnit.equals("吨") || freightUnit.equals("方"))) {
			// Toast.makeText(NewGoodInfo.this, "重量单位只能是吨、方其中一个",
			// Toast.LENGTH_LONG).show();
			// }
			final String freightUnit = mFreightUnitSpinner.getSelectedItem()
					.toString();

			if (TextUtils.isEmpty(startLocationLv1)
					|| TextUtils.isEmpty(startLocationLv2)
					|| TextUtils.isEmpty(endLocationLv1)
					|| TextUtils.isEmpty(endLocationLv2)
			// || TextUtils.isEmpty(freightName)
			// || TextUtils.isEmpty(freightTonnage)
			// || TextUtils.isEmpty(freightTruckAmountRequired)
			// || TextUtils.isEmpty(freightUnit)
			) {
				Toast.makeText(NewGoodInfo.this, "请填写相应字段", Toast.LENGTH_LONG)
						.show();
				return;
			}

			new AsyncTask<Void, Void, Object>() {
				ProgressDialog mDialog;

				@Override
				protected void onPostExecute(Object result) {
					if (result instanceof SoapPrimitive) {
						SoapPrimitive sp = (SoapPrimitive) result;
						try {
							Integer.valueOf(sp.toString());

							Toast.makeText(NewGoodInfo.this, "发布成功",
									Toast.LENGTH_LONG).show();

							Intent i = new Intent(NewGoodInfo.this,
									NewGoodInfoAfter.class);
							i.putExtra("startLocationLv1", startLocationLv1);
							i.putExtra("startLocationLv2", startLocationLv2);
							i.putExtra("startLocationLv3", startLocationLv3);
							i.putExtra("endLocationLv1", endLocationLv1);
							i.putExtra("endLocationLv2", endLocationLv2);
							i.putExtra("endLocationLv3", endLocationLv3);
							i.putExtra("setOffDate", setOffDate);
							i.putExtra("freightName", freightName);
							i.putExtra("freightTonnage", freightTonnage);
							i.putExtra("freightTruckLengthRequired",
									freightTruckLengthRequired);
							i.putExtra("contactName", contactName);
							i.putExtra("contactPhone", contactPhone);
							i.putExtra("attention", attention);
							i.putExtra("freightTruckTypeRequired",
									freightTruckTypeRequired);
							i.putExtra("freightTruckAmountRequired",
									freightTruckAmountRequired);
							//startActivity(i);
							finish();
						} catch (Exception e) {
							Toast.makeText(NewGoodInfo.this, sp.toString(),
									Toast.LENGTH_LONG).show();
						}
					} else {
						Toast.makeText(NewGoodInfo.this, "发布失败，请稍候重试",
								Toast.LENGTH_LONG).show();
					}
					mDialog.dismiss();
				};

				@Override
				protected void onPreExecute() {
					mDialog = ProgressDialog.show(NewGoodInfo.this, "", "发布中");
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient.companyPublicFreightMessage(
								mCertificate, startLocationLv1,
								startLocationLv2, startLocationLv3,
								endLocationLv1, endLocationLv2, endLocationLv3,
								freightName, freightTonnage,
								freightTruckLengthRequired,
								freightTruckTypeRequired,
								freightTruckAmountRequired, contactName,
								contactPhone, attention, setOffDate,
								freightUnit);
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					} catch (ParseException e) {
						return e;
					}
				}
			}.execute();
			break;
		case R.id.select_date:
			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int monthOfYear = c.get(Calendar.MONTH);
			int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);

			DatePickerDialog datePicker = new DatePickerDialog(this,
					new OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							Date date = new Date(year - 1900, monthOfYear,
									dayOfMonth);
							if(date.getTime() < System.currentTimeMillis()) {
								Toast.makeText(NewGoodInfo.this, "选择日期小于当前日期", Toast.LENGTH_SHORT).show();
								return;
							}
							mDateShow.setText(sDateFormat.format(date));
						}
					}, year, monthOfYear, dayOfMonth);
			datePicker.show();
			break;
		}
	}

	class GetNewGoodInfo extends AsyncTask<Void, Void, Object> {
		ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(NewGoodInfo.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (result instanceof Object[]) {
					Object[] values = (Object[]) result;
					SoapObject truckList = (SoapObject) values[0];
					// 03-01 22:24:43.300: D/(28205): result:
					// anyType{ArrayOfString=anyType{string=1; string=前四后八; };
					// ArrayOfString=anyType{string=2; string=高栏车; };
					// ArrayOfString=anyType{string=3; string=挂车; };
					// ArrayOfString=anyType{string=4; string=双桥车; };
					// ArrayOfString=anyType{string=5; string=前四后四; }; }, type:
					// SoapObject
					String[] trucks = new String[truckList.getPropertyCount()];
					for (int i = 0; i < truckList.getPropertyCount(); i++) {
						SoapObject truck = (SoapObject) truckList
								.getProperty(i);
						trucks[i] = truck.getPropertyAsString(1);
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							NewGoodInfo.this,
							R.layout.item_simple_dropdown_1line, trucks);
					mNeedCarModel.setAdapter(adapter);

					SoapObject myCurrentPlace = (SoapObject) values[1];
					String lv1 = myCurrentPlace.getProperty(0).toString();
					String lv2 = myCurrentPlace.getProperty(1).toString();
					String lv3 = myCurrentPlace.getProperty(2).toString();
					mFromProviceSelector.setProvice(lv1);
					mFromProviceSelector.setCity(lv2);
					mFromProviceSelector.setRegion(lv3);
				} else {
					AlertDialog.Builder builder = new Builder(NewGoodInfo.this);
					builder.setMessage("网络请求超时！");
					builder.setPositiveButton("重试",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new GetNewGoodInfo().execute();
								}
							});
					builder.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							});
					builder.show();
				}
			} catch (Exception e) {
			}

			mDialog.dismiss();
		};

		@Override
		protected Object doInBackground(Void... params) {
			try {
				Object[] values = new Object[2];
				values[0] = mWebServiceClient.commomGetTruckList(mCertificate);
				values[1] = mWebServiceClient
						.commonGetMyCurrentPlace(mCertificate);
				return values;
			} catch (IOException e) {
				e.printStackTrace();
				return e;
			} catch (XmlPullParserException e) {
				e.printStackTrace();
				return e;
			}
		}
	}

	SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
